/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.unice.miage.oobdoo.entity.Album;
import com.unice.miage.oobdoo.entity.Commentaire;
import com.unice.miage.oobdoo.entity.Note;
import com.unice.miage.oobdoo.entity.Partage;
import com.unice.miage.oobdoo.entity.Photo;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.enumeration.Statut;
import com.unice.miage.oobdoo.manager.AlbumManager;
import com.unice.miage.oobdoo.manager.CommentaireManager;
import com.unice.miage.oobdoo.manager.NoteManager;
import com.unice.miage.oobdoo.manager.PartageManager;
import com.unice.miage.oobdoo.manager.PhotoManager;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Remi
 */
@WebServlet(name = "AlbumServlet", urlPatterns = {"/AlbumServlet"})
public class AlbumServlet extends HttpServlet {

    @EJB
    private NoteManager noteManager;
    @EJB
    private PhotoManager photoManager;
    @EJB
    private UtilisateurManager utilisateurManager;
    @EJB
    private AlbumManager albumManager;
    @EJB
    private PartageManager partageManager;
    @EJB
    private CommentaireManager commentaireManager;

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");
        String forwardTo = "AlbumServlet?action=list";

        if (action != null) {
            if (action.equals("addPartage")) {

                String login = ((String) request.getParameter("login"));
                int idA = Integer.valueOf((String) request.getParameter("idAlbum"));
                Utilisateur u = utilisateurManager.getUtilisateurByLogin(login);

                Album a = albumManager.getAlbumById(idA);

                Partage p = partageManager.creerPartage(u, a);
                albumManager.addPartage(a, p);
                utilisateurManager.addPartage(u, p);

                //RENVOIE LA REPONSE EN JSON
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.println("{\"ret\":\"1\", \"login\":\""
                        + u.getLogin()
                        + "\",\"id\":\""
                        + u.getId()
                        + "\",\"idAlbum\":\""
                        + a.getId()
                        + "\"}");
            } else if (action.equals("deletePartage")) {

                int idU = Integer.valueOf((String) request.getParameter("idUtilisateur"));
                int idA = Integer.valueOf((String) request.getParameter("idAlbum"));

                Utilisateur u = utilisateurManager.getUtilisateurById(idU);
                Album a = albumManager.getAlbumById(idA);

                Partage p = partageManager.getPartageByUtilisateurAndAlbum(u, a);

                albumManager.deletePartage(a, p);
                utilisateurManager.deletePartage(u, p);
                partageManager.deletePartage(p);

                //RENVOIE LA REPONSE EN JSON
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                out.println("{\"ret\":\"1\", \"login\":\""
                        + u.getLogin()
                        + "\",\"id\":\""
                        + u.getId()
                        + "\"}");
            } else {
                if (action.equals("create")) {
                    String submit = request.getParameter("submit");
                    if (submit != null) {
                        String nom = request.getParameter("nom");
                        String description = request.getParameter("desc");
                        String statut = request.getParameter("statut");
                        Statut s = Statut.valueOf(statut);

                        HttpSession session = request.getSession(true);
                        String id = session.getAttribute("id").toString();

                        Utilisateur u = utilisateurManager.getUtilisateurById(Integer.valueOf(id));

                        Album a = albumManager.creerAlbum(u, nom, description, s);

                        utilisateurManager.addAlbum(u, a);

                        // Variable Application
                        session.setAttribute("albums", u.getAlbums());

                        int idAlbum = a.getId();

                        if (a != null) {
                            //utilisateurManager.addAlbum(u, a);
                            forwardTo = "album/add.jsp?ec=ok&id=" + idAlbum;
                        } else {
                            forwardTo = "album/add.jsp?ec=error";
                        }
                    } else {
                        forwardTo = "album/add.jsp";
                    }
                } else if (action.equals("modify")) {
                    int id = Integer.valueOf(request.getParameter("IdAlbum"));
                    Album a = albumManager.getAlbumById(id);


                    Enumeration en = request.getParameterNames();
                    while (en.hasMoreElements()) {
                        String key = (String) en.nextElement();
                        if (key.startsWith("photos_")) {
                            String[] tmp = key.split("_");
                            Photo p = photoManager.getPhotoById(Integer.valueOf(tmp[1]));
                            if (key.endsWith("_titre")) {
                                photoManager.updateName(p, request.getParameter(key));
                            } else if (key.endsWith("_description")) {
                                photoManager.updateDescription(p, request.getParameter(key));
                            }
                        }
                    }

                    request.setAttribute("id", id);
                    request.setAttribute("nom", a.getNom());
                    request.setAttribute("description", a.getDescription());
                    request.setAttribute("idAuteur", a.getAuteur().getId());
                    request.setAttribute("photographe", a.getAuteur().getLogin());
                    request.setAttribute("lstPhotos", a.getPhotos());
                    forwardTo = "album/album.jsp";

                    HttpSession session = request.getSession(true);
                    session.setAttribute("albums", a.getAuteur().getAlbums());


                } else if (action.equals("edit")) {
                    int id = Integer.valueOf(request.getParameter("IdAlbum"));
                    Album a = albumManager.getAlbumById(id);

                    request.setAttribute("id", id);
                    request.setAttribute("idAuteur", a.getAuteur().getId());
                    request.setAttribute("nom", a.getNom());
                    request.setAttribute("add", 0);


                    String add = request.getParameter("add");
                    if (add != null) {
                        request.setAttribute("add", 1);
                    }

                    String submit = request.getParameter("submit");
                    if (submit != null) {
                        System.out.println("traitement des photos envoyees");

                        int countPictures = Integer.valueOf(request.getParameter("uploader_count"));
                        String name, outfile, etat;

                        String path = this.getServletContext().getInitParameter("PATH");
                        String albumDir = path + "upload/" + a.getAuteur().getId() + "/" + a.getId() + "/";
                        for (int i = 0; i < countPictures; i++) {
                            name = request.getParameter("uploader_" + i + "_name");
                            etat = request.getParameter("uploader_" + i + "_status");
                            if (etat.equals("done")) {
                                // Ajout de la photo à l'album
                                int mid = name.lastIndexOf(".");
                                String fname = name.substring(0, mid);
                                String ext = name.substring(mid + 1, name.length());

                                Photo p = photoManager.creerPhoto(a, "", "", name, fname + "_thumb_224." + ext, fname + "_thumb_140." + ext, fname + "_thumb_500." + ext);
                                albumManager.addPhoto(a, p);
                            }
                        }

                        request.setAttribute("add", 0);
                    }
                    // RECUPERATION LISTE PHOTOS
                    request.setAttribute("lstPhotos", a.getPhotos());
                    HttpSession session = request.getSession(true);
                    session.setAttribute("albums", a.getAuteur().getAlbums());
                    forwardTo = "album/edit.jsp";

                } else if (action.equals("view")) {
                    HttpSession session = request.getSession(true);

                    int id = Integer.valueOf(request.getParameter("IdAlbum"));
                    int idSession = Integer.valueOf(session.getAttribute("id").toString());
                    Album a = albumManager.getAlbumById(id);
                    Utilisateur u = utilisateurManager.getUtilisateurById(idSession);

                    if (albumManager.isAuthorizedToView(a, u)) {
                        request.setAttribute("id", id);
                        request.setAttribute("nom", a.getNom());
                        request.setAttribute("description", a.getDescription());
                        request.setAttribute("idAuteur", a.getAuteur().getId());
                        request.setAttribute("photographe", a.getAuteur().getLogin());
                        request.setAttribute("lstPhotos", a.getPhotos());


                        // UPDATE DE LA NOTIFICATION
                        Collection<Partage> ps = a.getPartages();
                        for (Partage p : ps) {
                            if (p.getUtilisateur().getId() == u.getId()) {
                                partageManager.updateViewPartage(p, true);
                                break;
                            }
                        }

                        String message = request.getParameter("message");

                        if (message != null) {
                            switch (Integer.valueOf(message)) {
                                case 0:
                                    request.setAttribute("message", "Erreur lors de l'importation. Veuillez recommencer.");
                                    break;
                                case 1:
                                    request.setAttribute("message", "Exportation OK !");
                                    break;
                            }
                        }

                        forwardTo = "album/album.jsp";
                    } else {
                        forwardTo = "AlbumServlet?action=list";
                    }
                } else if (action.equals("apicture")) {
                    int id = Integer.valueOf(request.getParameter("id"));
                    String p = albumManager.getOnePictureByAlbumId(id);
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println(p);
                    return;
                } else if (action.equals("list")) {
                    HttpSession session = request.getSession(true);

                    int idU = Integer.valueOf(session.getAttribute("id").toString());
                    Utilisateur u = utilisateurManager.getUtilisateurById(idU);

                    Collection<Album> albums = u.getAlbums();

                    request.setAttribute("albums", albums);
                    forwardTo = "album/list.jsp";
                } else if (action.equals("shared")) {
                    HttpSession session = request.getSession(true);

                    int idU = Integer.valueOf(session.getAttribute("id").toString());
                    Utilisateur u = utilisateurManager.getUtilisateurById(idU);

                    Collection<Album> partage = u.getAlbumsPartagesValide();

                    request.setAttribute("albums", partage);
                    forwardTo = "album/list.jsp";
                } else if (action.equals("public")) {
                    request.setAttribute("albums", albumManager.getAllAlbumsPublic());
                    forwardTo = "album/list.jsp";
                } else if (action.equals("partager")) {

                    int id = Integer.valueOf(request.getParameter("id"));

                    Album a = albumManager.getAlbumById(id);
                    Collection<Utilisateur> utilisateurs = a.getUtilisateursPartagesValide();
                    request.setAttribute("utilisateurs", utilisateurs);
                    request.setAttribute("id", a.getId());
                    request.setAttribute("nomAlbum", a.getNom());
                    forwardTo = "album/partager.jsp";
                } else if (action.equals("delete")) {
                    HttpSession session = request.getSession(true);

                    int id = Integer.valueOf(request.getParameter("IdAlbum"));
                    int idSession = Integer.valueOf(session.getAttribute("id").toString());
                    Album a = albumManager.getAlbumById(id);
                    Utilisateur u = utilisateurManager.getUtilisateurById(idSession);

                    if (albumManager.isAuthorizedToView(a, u)) {

                        Object[] photos = a.getPhotos().toArray();

                        for (int i = 0; i < photos.length; i++) {
                            Photo p = (Photo) photos[i];
                            Object[] commentaires = p.getCommentaires().toArray();
                            for (int j = 0; j < commentaires.length; j++) {

                                Commentaire c = (Commentaire) commentaires[j];
                                Utilisateur auteur = c.getAuteur();

                                photoManager.deleteCommentaire(p, c);
                                utilisateurManager.deleteCommentaire(auteur, c);
                                commentaireManager.deleteCommentaire(c);
                            }

                            albumManager.deletePhoto(a, p);
                            photoManager.deletePhoto(p);
                            removeFilePhoto(p);
                        }

                        a = albumManager.getAlbumById(id);
                        u = utilisateurManager.getUtilisateurById(idSession);

                        Object[] partages = a.getPartages().toArray();

                        for (int i = 0; i < partages.length; i++) {

                            Partage p = (Partage) partages[i];

                            Utilisateur user = p.getUtilisateur();

                            albumManager.deletePartage(a, p);
                            utilisateurManager.deletePartage(user, p);
                            partageManager.deletePartage(p);
                        }

                        a = albumManager.getAlbumById(id);
                        u = utilisateurManager.getUtilisateurById(idSession);

                        Object[] notes = a.getNotes().toArray();

                        for (int i = 0; i < notes.length; i++) {

                            Note n = (Note) notes[i];

                            albumManager.deleteNote(a, n);
                            utilisateurManager.deleteNote(n.getAuteur(), n);
                            noteManager.deleteNote(n);
                        }

                        utilisateurManager.deleteAlbum(u, a);
                        albumManager.deleteAlbum(a);
                        removeFolderAlbum(a);

                    }
                    forwardTo = "AlbumServlet?action=list";
                } else {
                    forwardTo = "album/list.jsp";
                }

                RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                dp.forward(request, response);
            }
        }
    }

    private void removeFilePhoto(Photo p) {
        try {
            String path = this.getServletContext().getInitParameter("PATH") + "upload/" + p.getAlbum().getAuteur().getId() + "/" + p.getAlbum().getId() + "/";

            File file = new File(path + p.getPathFile());
            File thumbH = new File(path + p.getPathThumbHome());
            File thumbL = new File(path + p.getPathThumbList());
            File thumbP = new File(path + p.getPathThumbPhoto());

            Files.delete(file.toPath());
            Files.delete(thumbH.toPath());
            Files.delete(thumbL.toPath());
            Files.delete(thumbP.toPath());
        } catch (IOException ex) {
            Logger.getLogger(AlbumServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void removeFolderAlbum(Album a) {
        String path = this.getServletContext().getInitParameter("PATH") + "upload/" + a.getAuteur().getId() + "/" + a.getId();

        File dir = new File(path);
        deleteDir(dir);
    }
     
    private boolean deleteDir(File dir)
    {
        if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    // The directory is now empty so delete it
    return dir.delete();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
